<template>
  <div>
    <!-- 基本信息 -->
    <div v-loading="personInfoLoading">
      <el-row>
        <el-col :span="20">
          <el-divider content-position="left">
            <span style="font-size: 16px;color: #353434;font-weight: bold;">基本信息</span>
          </el-divider>
        </el-col>
        <el-col :span="4" class="gl_pt_10 gl_pl_10">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="openEditPersonInfo">编辑信息</el-button>
        </el-col>
      </el-row>
      <el-row class="person_info" type="flex" align="middle">
        <el-col :span="3" align="left">
          <div class="person_info_img">
            <show-avatar
              :src="getStaticAvatarUrl(individualInfo.imagePath)"
              width="76px"
              height="76px"
              shape="circle"
              border="4px solid #93B3F0"
            />
          </div>
        </el-col>
        <el-col :span="21">
          <el-row style="margin-bottom: 8px;">
            <el-col :span="16">
              <span class="label_name">姓名：</span>
              <span class="label_content">{{ individualInfo.name }}</span>
            </el-col>
          </el-row>
          <el-row style="margin-bottom: 8px;">
            <el-col :span="7">
              <span class="label_name">证件号码：</span>
              <span class="label_content">{{ individualInfo.idCardNumber }}</span>
            </el-col>
          </el-row>
          <el-row style="margin-bottom: 8px;">
            <el-col :span="5">
              <span class="label_name">出生日期：</span>
              <span class="label_content">{{ individualInfo.birthDate && individualInfo.birthDate.substring(0, 10) }}</span>
            </el-col>
            <el-col :span="3">
              <span class="label_name">性别：</span>
              <span class="label_content">{{ individualInfo.gender && individualInfo.gender.name }}</span>
            </el-col>
            <el-col :span="6">
              <span class="label_name">国籍：</span>
              <span class="label_content">
                <template v-for="ktem in dict.country">
                  {{ ktem.code === individualInfo.nationality ? ktem.value : '' }}
                </template>
              </span>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <span class="label_name">身份标签：</span>
              <el-tag v-for="(item, index) in tagList" :key="item.id" class="gl_mr_10" size="mini" :closable="tagList.length > 1" :type="tagsColorTheme[index]" @close="deleteTag(item)">
                {{ item.registerTagType && item.registerTagType.name }}
              </el-tag>
              <el-tooltip v-if="dict.registerTagType && tagList.length < dict.registerTagType.length" effect="dark" content="点击新增角色标签" placement="right">
                <el-button class="add_tag" size="mini" @click="openEditTags">+</el-button>
              </el-tooltip>
            </el-col>
            <!-- <el-col :span="24" class="gl_mt_15">
              <el-button type="primary" size="mini" @click="openEditPersonInfo">编辑</el-button>
            </el-col> -->
          </el-row>
        </el-col>
      </el-row>
    </div>
    <div v-if="currentUserType && currentUserType.registerId" v-loading="organizationInfoLoading">
      <el-row class="organization_info">
        <el-col :span="20">
          <el-divider content-position="left">
            <span style="font-size: 16px;color: #353434;font-weight: bold;">所属机构/团体</span>
          </el-divider>
        </el-col>
        <el-col :span="4" class="gl_pt_10 gl_pl_10">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="openJoinOrgan">加入机构</el-button>
        </el-col>
      </el-row>
      <!-- 所属机构/团体 -->
      <el-row :gutter="15" class="gl_mt_10">
        <template v-if="delegationInfo.length">
          <el-col v-for="(item, index) in delegationInfo" :key="index" :span="8" class="delegation_item">
            <el-card v-if="item" shadow="hover" :body-style="{ padding: '10px', height: '115px' }">
              <el-row :gutter="15" type="flex" align="middle">
                <el-col :span="7" align="center">
                  <el-avatar shape="circle" :size="76" fit="scale-down" :src="getStaticAvatarUrl(item.imagePath)" />
                </el-col>
                <el-col :span="17">
                  <div class="gl_ft_weight gl_mb_5 gl_ellipsis" :title="item.name">{{ item.name }}</div>
                  <div class="gl_mb_5 gl_ellipsis">
                    <span class="label_name">地区：</span>
                    <span class="label_content">{{ addressDataForCheck(item) }}</span>
                  </div>
                  <div class="gl_mb_5">
                    <span class="label_name">类型：</span>
                    <span class="label_content">{{ item.delegationType && item.delegationType.name }}</span>
                  </div>
                  <div align="right">
                    <el-button size="mini" @click="handleSubmitDeleteOrgan(item.id)">退出</el-button>
                  </div>
                </el-col>
              </el-row>
            </el-card>
          </el-col>
        </template>
        <el-col v-else :span="24">
          <div class="gl_noData">
            <p>暂无数据</p>
          </div>
        </el-col>
      </el-row>
    </div>
    <!-- 个人编辑弹框 -->
    <el-dialog class="gl_dialog_TitleLine" title="编辑" :visible.sync="dialogVisible" :close-on-click-modal="false" width="1200px">
      <el-tabs v-model="activeTab" class="gl_tabs" type="card">
        <el-tab-pane label="基础信息" name="0">
          <personal-info ref="refPersonalInfo" :user-data="individualInfo" :is-default-check="!!individualInfo.isApproved" />
        </el-tab-pane>
        <el-tab-pane label="会员信息" name="1">
          <!-- 中跆协会员 -->
          <modMemberInfo ref="refModMemberInfo" :dict="dictRoot.dict" :user-data="individualInfo" form-size="mini" :hide-title="true" :hide-style="true" />
        </el-tab-pane>
        <el-tab-pane label="段位信息" name="2">
          <!-- 中跆协级位段位 -->
          <modTkwChiDan ref="refModTkwChiDan" :dict="dictRoot" :user-data="individualInfo" form-size="mini" :hide-style="true" class="gl_mb_20" />
          <!-- 国际台协段位 -->
          <modTkwIntDan ref="refModTkwIntDan" :dict="dictRoot" :user-data="individualInfo" form-size="mini" :hide-style="true" />
        </el-tab-pane>
      </el-tabs>

      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogVisible = false">{{ $t('button.cancel') }}</el-button>
        <el-button size="mini" type="primary" :loading="submitLoading" @click="submitRefresh">{{ $t('button.submit') }}</el-button>
      </div>
    </el-dialog>
    <edit-tags ref="editTags" @refreshPage="getTagList" />
    <join-organ ref="joinOrgan" @refreshPage="getCurrentDelegationInfo" />
  </div>
</template>
<script>
import { mapState, mapActions } from 'vuex';
import { translateByCode } from '@/lib/getTransData';
import { CopyData } from '@/lib';
import {
  api_GET_EventsManagementRegisterId,
  api_GET_EventsManagementRegisterTag,
  api_DELETE_EventsManagementRegisterTagId,
  api_PUT_EventsManagementRegisterId,
  api_GET_EventsManagementDelegation,
  api_POST_EventsManagementRegister,
  api_POST_EventsManagementRegisterQuitDelegationDelegationId
} from '@/extend/api/gameswaggerApi/app';
import editTags from './editTags';
import personalInfo from '@/components/PersonalInfo';
import joinOrgan from './joinOrgan';

import modMemberInfo from '@/views/home/train/components/modMemberInfo';
import modTkwChiDan from '@/views/home/train/components/modTkwChiDan';
import modTkwIntDan from '@/views/home/train/components/modTkwIntDan';

export default {
  components: {
    editTags,
    personalInfo,
    joinOrgan,
    modMemberInfo,
    modTkwChiDan,
    modTkwIntDan
  },
  data() {
    return {
      personInfoLoading: false,
      individualInfo: {},
      // 标签列表
      tagList: [],
      dialogVisible: false,
      submitLoading: false,
      organizationInfoLoading: false,
      delegationInfo: [],
      tagsColorTheme: ['primary', 'success', 'info', 'warning'],
      activeTab: '0'
    };
  },
  computed: {
    ...mapState({
      dictRoot: state => state.dict,
      dict: state => state.dict.dict,
      cache: state => state.dict.cache,
      currentUserType: state => state.user.currentUserType,
      tags: state => state.user.tags
    })
  },
  watch: {
    dialogVisible(val) {
      if (!val) {
        this.$refs.refPersonalInfo.clearInsideUserData();
      }
    }
    // currentUserType: {
    //   handler(val) {
    //     if (!val) return;
    //     this.getIndividualInfo();
    //     this.getTagList();
    //     this.getCurrentDelegationInfo();
    //   }
    // },
    // tags: {
    //   handler(val, old) {
    //     if (JSON.stringify(val) !== JSON.stringify(old)) {
    //       this.getTagList();
    //     }
    //   }
    // }
  },
  created() {
    this.getDict();
    this.getDictByType(['district']);
    console.log('个人首页');
    if (this.currentUserType) {
      this.getIndividualInfo();
      this.getTagList();
      this.getCurrentDelegationInfo();
    }
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict', getDictByType: 'dict/getDictByType' }),
    getIndividualInfo() {
      return new Promise((resolve, reject) => {
        if (!this.currentUserType.registerId) return;
        this.personInfoLoading = true;
        api_GET_EventsManagementRegisterId(
          this.currentUserType.registerId,
          { IncludeGender: true, IncludeIdCardType: true }
        ).then(res => {
          this.individualInfo = res;
          this.personInfoLoading = false;
          this.$store.dispatch('user/getSaveCurrentUserIndInfo', res);
          resolve(res);
        }, error => {
          this.personInfoLoading = false;
          this.$message({ type: 'error', message: '获取个人信息失败！' + (error.error && error.error.message || '') });
          reject(error);
        });
      });
    },
    // 获取个人标签
    getTagList() {
      return new Promise((resolve, reject) => {
        api_GET_EventsManagementRegisterTag({
          RegisterId: this.currentUserType.registerId,
          IncludeRegisterTagType: true
        }).then(res => {
          this.tagList = res.items || [];
          this.$store.dispatch('user/getSaveCurrentUserTags', this.tagList);
        }, error => {
          this.$message({ type: 'error', message: '获取个人标签失败！' + (error.error && error.error.message || '') });
        });
      });
    },
    // 删除个人标签
    deleteTag(tag) {
      this.$confirm(`您确定要删除【${tag.registerTagType.name}】标签吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.personInfoLoading = true;
        api_DELETE_EventsManagementRegisterTagId(tag.id).then(() => {
          this.personInfoLoading = false;
          this.getTagList();
        }, error => {
          this.personInfoLoading = false;
          this.$message({ type: 'error', message: '删除失败！' + (error.error && error.error.message || '') });
        });
      });
    },
    openEditTags() {
      this.$refs.editTags.open(this.tagList);
    },
    openEditPersonInfo() {
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.refPersonalInfo.init();
      });
    },
    submitRefresh() {
      this.$refs.refPersonalInfo.getInsideUserData().then(res => {
        this.createRegisterInput = res;
        this.createRegisterInput.isCurrentUser = true;
        this.createRegisterInput.joinCurrentDelegation = false;
        this.createRegisterInput.registerTypeCode = this.createRegisterInput.registerTypeCode || 'I';
        this.getFormsData();
      });
    },
    // 获取各个表单数据
    getFormsData () {
      const _all = [
        this.$refs['refModMemberInfo'].getInsideUserData(),
        this.$refs['refModTkwChiDan'].getInsideUserData(),
        this.$refs['refModTkwIntDan'].getInsideUserData()
      ];

      Promise.all(_all)
        .then(
          res => {
            this.mergeFormDataToVO(res);

            if (this.currentUserType.registerId) {
              this.updateMemberInfo();
            } else {
              this.addMemberInfo();
            }
          }
        )
        .catch(
          error => {
            console.log('error: ', error);
            this.$message({
              message: `请先完善必填信息`,
              type: 'warning',
              showClose: true
            });
            if (error.component === 'memberInfo') {
              this.activeTab = '1';
            }
            if (error.component === 'tkwIntDan' || error.component === 'tkwChiDan') {
              this.activeTab = '2';
            }
          }
        );
    },
    // 将数据合并到VO
    mergeFormDataToVO (list) {
      const _this = this;
      for (let i = 0; i < list.length; i++) {
        const item = list[i];
        CopyData(item, _this.createRegisterInput);
      }
    },
    // 新增个人信息
    addMemberInfo() {
      // 将空字符串转为Null, 部分后端类型不支持null. 所以移除为空字段
      for (const k in this.createRegisterInput) {
        const ktem = this.createRegisterInput[k];
        if (ktem === '' || ktem === null) {
          // this.createRegisterInput[k] = null;
          delete this.createRegisterInput[k];
        }
      }
      this.submitLoading = true;
      api_POST_EventsManagementRegister(this.createRegisterInput).then(() => {
        this.submitLoading = false;
        this.dialogVisible = false;
        this.getIndividualInfo();
        this.$store.dispatch('user/getInfo');
        this.$store.dispatch('user/getCurrentUserType');
        this.$message({ type: 'success', message: '操作成功' });
      }, error => {
        this.$message({ type: 'error', message: (error.error && error.error.message) });
        this.submitLoading = false;
      });
    },
    // 更新个人信息
    updateMemberInfo() {
      this.submitLoading = true;
      api_PUT_EventsManagementRegisterId(this.currentUserType.registerId, this.createRegisterInput).then(() => {
        this.submitLoading = false;
        this.dialogVisible = false;
        this.getIndividualInfo();
        this.$message({ type: 'success', message: '操作成功' });
      }, error => {
        this.$message({ type: 'error', message: (error.error && error.error.message) });
        this.submitLoading = false;
      });
    },
    // 获取当前所属机构信息
    getCurrentDelegationInfo() {
      if (!(this.currentUserType && this.currentUserType.registerId)) return;
      this.organizationInfoLoading = true;
      const _qo = {
        RegisterId: this.currentUserType.registerId,
        IncludeDelegation: true,
        IncludeDelegationType: true
      };
      api_GET_EventsManagementDelegation(_qo).then(res => {
        this.organizationInfoLoading = false;
        this.delegationInfo = res.items || [];
      }, error => {
        this.organizationInfoLoading = false;
        this.$message({ type: 'error', message: '获取当前所属机构信息失败！' + (error.error && error.error.message || '') });
      });
    },
    // 退出团体
    handleSubmitDeleteOrgan(id) {
      this.$confirm(`您确定要退出当前团体吗？`, '提示', {
        confirmButtonText: translateByCode('alert.confirm'),
        cancelButtonText: translateByCode('alert.cancel'),
        type: 'warning'
      }).then(() => {
        api_POST_EventsManagementRegisterQuitDelegationDelegationId(id).then(res => {
          this.getCurrentDelegationInfo();
          this.$message({ type: 'success', message: '操作成功' });
        });
      });
    },
    openJoinOrgan() {
      this.$refs.joinOrgan.open(this.currentUserType.registerId);
    },
    findDictDataByCode (dictKey, code) {
      const _dict = this.dict[dictKey];
      if (_dict) {
        return _dict.find(item => item.code === code) || {};
      } else {
        return {};
      }
    },
    getStaticAvatarUrl(relativeUrl) {
      if (relativeUrl) {
        return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
      } else {
        return require('@/assets/images/face_default.png');
      }
    },
    addressDataForCheck (data) {
      const _provinceCode = data.provinceCode;
      const _cityCode = data.cityCode;
      const _countyCode = data.countyCode;
      let _provinceData;
      let _cityData;
      let _countyData;
      if (_provinceCode && this.cache.district) {
        _provinceData = this.cache.district.find(item => item.code === _provinceCode);
      }
      if (_cityCode && _provinceData) {
        _cityData = _provinceData.children.find(item => item.code === _cityCode);
      }
      if (_countyCode && _cityData) {
        _countyData = _cityData.children.find(item => item.code === _countyCode);
      }
      return `${_provinceData ? _provinceData.name : ''} ${_cityData ? _cityData.name : ''} ${_countyData ? _countyData.name : ''}`;
    }
  }
};
</script>

<style>
  .step_btn {
    padding-top: 48px;
  }

  .step_btn .el-button{
    border-radius: 8px;
  }
  .step_btn .el-button + .el-button {
    margin-left: 24px;
  }

  .box_wrap {
    padding: 30px 20px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0px 10px 36px 0px rgba(0, 0, 0, 0.08);
  }
  .box_wrap_title {
    font-size: 16px;
    font-weight: 500;
    line-height: 22px;
    color: #353434;
    margin-bottom: 20px;
  }
</style>

<style scoped>
.person_info_img {
  text-align: center;
}
.person_info_img .show_img {
  width: 76px;
  height: 76px;
  border-radius: 50%;
  border: 4px solid #93B3F0;
  vertical-align: middle;
}
.label_name {
  font-size: 14px;
  font-weight: bold;
  color: rgba(0, 0, 0, 0.8);
}
.label_content {
  color: #333;
  font-size: 14px;
}
.add_tag {
  height: 21px;
  line-height: 19px;
  padding-top: 0;
  padding-bottom: 0;
  vertical-align: middle;
}
</style>
